package com.sls.nzdapplication.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.esri.arcgisruntime.geometry.Point;
import com.hjq.widget.view.ClearEditText;
import com.hjq.widget.view.RegexEditText;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.markfrain.formview.view.FormEditView;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.AppActivity;
import com.sls.nzdapplication.db.utils.DyEquipmentLineUtil;
import com.sls.nzdapplication.db.utils.DyEquipmentUtil;
import com.sls.nzdapplication.db.utils.SwitchEquipmentUtil;
import com.sls.nzdapplication.db.utils.SwitchUtil;
import com.sls.nzdapplication.model.DyEquipment;
import com.sls.nzdapplication.model.DyEquipmentLine;
import com.sls.nzdapplication.model.ShowSwitch;
import com.sls.nzdapplication.model.Switch;
import com.sls.nzdapplication.model.SwitchEquipment;
import com.sls.nzdapplication.ui.custom.CableWellPhotoView;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.util.UuidUtils;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.text.DecimalFormat;
import java.text.Format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import es.dmoral.toasty.Toasty;
import me.kareluo.ui.OptionMenu;
import me.kareluo.ui.OptionMenuView;
import me.kareluo.ui.PopupMenuView;

public class PdxEquipmentActivity extends AppActivity implements View.OnClickListener,CableWellPhotoView.OnclickPhotoListener{
    NiceSpinner dxxhView,typeView,dxlxView,ljfsView,sbztView,cxdlxhView;
    TextView latView,lonView;
    ImageView qxxxRight,qdsbRight,addswitch;
    TableRow qxxxInfoView,sbztInfoView,qdsbInfoView,ljfsInfoView,cxkgInfoView,cxdlxhInfoView;
    SmartTable switchTable;
    private ClearEditText qxxxView,qssbView;
    private RegexEditText equipmentCxkgView;
    TextView saveEquipmentView;
    private DyEquipmentUtil dyEquipmentUtil;

    private boolean isNew = true;

    private String equipmentId = "";

    private String type;

    private String lineId;

    private Double lat = 0.0;

    private Double lon = 0.0;

    private SwitchUtil switchUtil;

    private LinearLayout dataView;


    private String photoType;

    private CableWellPhotoView equipmentQmPhotoView;

    private CableWellPhotoView equipmentMpPhotoView;

    private CableWellPhotoView equipmentQxPhotoView;

    private String clickEquipmentId = "";

    private String clickSwitchId = "";

    private DyEquipmentLineUtil equipmentLineUtil;

    private FormEditView previousEquipmenNameView;

    private ImageView rtEquipmentTypeView;

    private SwitchEquipmentUtil switchEquipmentUtil;

    private LinearLayout tableTitleView;

    private AutoCompleteTextView autoCompleteTextViewNameView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pdx_equipment;
    }

    @Override
    protected void initView() {
        autoCompleteTextViewNameView = findViewById(R.id.equipment_name);
        dxxhView = (NiceSpinner) findViewById(R.id.dy_equipment_dxxh);
        typeView = (NiceSpinner) findViewById(R.id.dy_equipment_type);
        ljfsView = (NiceSpinner) findViewById(R.id.dy_equipment_ljfs);
        sbztView = (NiceSpinner) findViewById(R.id.dy_equipment_sbzt);
        qssbView = findViewById(R.id.equipment_qdsb);
        qssbView.setFocusable(false);
        latView = findViewById(R.id.equipment_lat);
        lonView = findViewById(R.id.equipment_lon);
        qxxxRight = findViewById(R.id.qxxx_right);
        qxxxInfoView = findViewById(R.id.qxxx_info_view);
        sbztInfoView = findViewById(R.id.sbzt_info_view);
        qxxxView = findViewById(R.id.equipment_qxxx);
        addswitch = findViewById(R.id.add_switch);
        equipmentCxkgView = findViewById(R.id.equipment_cxkg);
        cxkgInfoView = findViewById(R.id.cxkg_info_view);
        switchTable = findViewById(R.id.switch_table);

        switchTable.getConfig().setShowXSequence(false);
        switchTable.getConfig().setShowYSequence(false);
        switchTable.getConfig().setShowTableTitle(false);
        switchTable.getConfig().setColumnTitleStyle (new FontStyle(30, getResources().getColor(R.color.colorPrimaryDark)));
        switchTable.getConfig().setMinTableWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth());
        cxdlxhView = findViewById(R.id.dy_equipment_cxdlxh);
        cxdlxhInfoView = findViewById(R.id.cxdlxh_info_view);
        ljfsInfoView = findViewById(R.id.ljfs_info_view);
        qdsbInfoView = findViewById(R.id.qdsb_info_view);
        saveEquipmentView = findViewById(R.id.save_equipment);
        equipmentQmPhotoView = findViewById(R.id.equipment_qm_photo);
        equipmentQmPhotoView.setOnclickPhotoListener(this);


        equipmentMpPhotoView = findViewById(R.id.equipment_mp_photo);
        equipmentMpPhotoView.setOnclickPhotoListener(this);

        equipmentQxPhotoView = findViewById(R.id.equipment_qx_photo);
        equipmentQxPhotoView.setOnclickPhotoListener(this);
        initListener();

    }

    private void initListener(){
        qxxxRight.setOnClickListener(this);
        saveEquipmentView.setOnClickListener(this);
        addswitch.setOnClickListener(this);
        equipmentLineUtil = new DyEquipmentLineUtil(getApplicationContext());
        switchEquipmentUtil = new SwitchEquipmentUtil(getApplicationContext());
        dyEquipmentUtil = new DyEquipmentUtil(getApplicationContext());
        switchUtil = new SwitchUtil(getApplicationContext());
    }

    @Override
    protected void initData() {
        List<String> projName1 = new ArrayList<>();



        List<String> projName4 = new ArrayList<>();
        projName4.add("架空");
        projName4.add("入地");
        ljfsView.attachDataSource(projName4);
        List<String> projName5 = new ArrayList<>();
        projName5.add("在运");
        projName5.add("停运");
        projName5.add("未投运");
        sbztView.attachDataSource(projName5);

        List<String> projName6 = new ArrayList<>();
        projName6.add("YJV22-3*300");
        projName6.add("YJV22-3*350");
        projName6.add("YJV22-4*95");
        projName6.add("YJV22-4*240");
        projName6.add("VV22-4*240");
        projName6.add("YJV22-4*150");
        projName6.add("YJV22-3*240");
        projName6.add("YJV22-4*70");
        projName6.add("YJV22-4*50");
        projName6.add("YJV22-4*35");
        projName6.add("YJV22-4*16");
        projName6.add("YJV22-3*185+1*95");
        projName6.add("YJV22-3*150+1*50");
        projName6.add("YJV22-3*50+1*25");
        projName6.add("YJV22-3*25+1*16");
        projName6.add("YJV22-3*6+1*10");
        projName6.add("YJV22-3*240+1*12");
        projName6.add("YJV22-3*35+1*16");
        projName6.add("YJV22-4*120");
        cxdlxhView.attachDataSource(projName6);


        Intent intent = getIntent();
        if(null !=intent && intent.getStringExtra("equipmentId")!=null){
            isNew = false;
            equipmentId = intent.getStringExtra("equipmentId");
            DyEquipment equipment = dyEquipmentUtil.listOneDyEquipment(equipmentId);
            autoCompleteTextViewNameView.setText(equipment.getName());
            typeView.setText(equipment.getType());
            latView.setText(String.valueOf(equipment.getLat()));
            lonView.setText(String.valueOf(equipment.getLon()));
            cxdlxhView.setText(equipment.getCxdxxh()==null?"":equipment.getCxdxxh());
            ljfsView.setText(equipment.getLxfs()==null?"":equipment.getLxfs());
            sbztView.setText(equipment.getSbzt()==null?"":equipment.getSbzt());
            qxxxView.setText(equipment.getQxxx()==null?"":equipment.getQxxx());
            type = equipment.getType();
            if(type.equals("变压器")){
                hideView();
            }
            lineId = equipment.getAreaId();
            DyEquipment ex = dyEquipmentUtil.listOneDyEquipment(equipment.getPreviousEquipmentId());
            String sname = "";
            if(ex!=null){
                if(ex.getType().equals("配电箱") || ex.getType().equals("变压器")){
                    clickSwitchId = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId).get(0).getSid();
                    sname = switchUtil.listOneSwitch(clickSwitchId).getName();
                }
                qssbView.setText(ex.getName()+sname);
                clickEquipmentId = equipment.getPreviousEquipmentId();
            }

        }
        else if(null !=intent && intent.getBundleExtra("params") != null){
            Bundle bundle = intent.getBundleExtra("params");
            lat = bundle.getDouble("lat");
            lon = bundle.getDouble("lon");
            type = bundle.getString("type");
            clickEquipmentId = bundle.getString("clickE");
            clickSwitchId = bundle.getString("clickS");
            lineId = bundle.getString("lineId");
            equipmentId = UuidUtils.getStringID();
            System.err.println(latView);
            latView.setText(String.valueOf(lat));
            lonView.setText(String.valueOf(lon));
            typeView.setText(type);
            if(type.equals("变压器")){
                hideView();
            }
            DyEquipment ex = dyEquipmentUtil.listOneDyEquipment(clickEquipmentId);
            if(ex!=null){
                qssbView.setText(ex.getName());
            }
        }

        if(isNew && dyEquipmentUtil.queryDyEquipmentByAreaIdAndByq2(lineId).size()==0){
            projName1.add("配电箱");
            projName1.add("变压器");
        }else{
            projName1.add("配电箱");
        }
        typeView.attachDataSource(projName1);

        typeView.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if(position==0){
                    showView();
                }else{
                    hideView();
                }
            }
        });
        equipmentQmPhotoView.initData("dyEquipment",equipmentId,"qm");
        equipmentMpPhotoView.initData("dyEquipment",equipmentId,"mp");
        equipmentQxPhotoView.initData("dyEquipment",equipmentId,"qx");
        showDataView();
    }

    @Override
    public void onRightClick(View view) {
        new PopWindow.Builder(this)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .setTitle("你确定要删除当前数据！！")
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        delData();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .show();
    }

    private void delData(){
        boolean hasSw = false;
        List<Switch> switchList = switchUtil.querySwitchByeId(equipmentId);
        for(Switch s:switchList){
            if(switchEquipmentUtil.querySwitchEquipmentBySid(s.getId()).size()>0){
                hasSw = true;
            }
        }
        if(hasSw){
            Toasty.error(getApplicationContext(), "有已连接开关无法删除此设备！", Toast.LENGTH_LONG, true).show();
            return;
        }
        for(Switch s:switchList){
            switchUtil.deleteSwitch(s);
        }
        List<DyEquipmentLine> equipmentLineList = equipmentLineUtil.queryEquipmentLineByEid(equipmentId);
        for(DyEquipmentLine equipmentLine:equipmentLineList){
            equipmentLineUtil.deleteDyEquipmentLine(equipmentLine);
        }
        dyEquipmentUtil.deleteDyEquipment(dyEquipmentUtil.listOneDyEquipment(equipmentId));
        this.finish();
    }

    private void showDataView(){
        List<Switch> switchList = switchUtil.querySwitchByeId(equipmentId);
        equipmentCxkgView.setText(String.valueOf(switchList.size()));
        showData(switchList);
    }

    private void showView(){
        cxdlxhInfoView.setVisibility(View.VISIBLE);
        cxkgInfoView.setVisibility(View.VISIBLE);
        ljfsInfoView.setVisibility(View.VISIBLE);
        qxxxInfoView.setVisibility(View.VISIBLE);
        sbztInfoView.setVisibility(View.VISIBLE);
        qdsbInfoView.setVisibility(View.VISIBLE);
        equipmentQxPhotoView.setVisibility(View.VISIBLE);
        switchTable.setVisibility(View.VISIBLE);
    }

    private void hideView(){
        cxdlxhInfoView.setVisibility(View.GONE);
        cxkgInfoView.setVisibility(View.GONE);
        ljfsInfoView.setVisibility(View.GONE);
        qxxxInfoView.setVisibility(View.GONE);
        sbztInfoView.setVisibility(View.GONE);
        qdsbInfoView.setVisibility(View.GONE);
        equipmentQxPhotoView.setVisibility(View.GONE);
        switchTable.setVisibility(View.GONE);
    }

    private void addKg(){
        Format f1 = new DecimalFormat("000");
        int number = Integer.valueOf(equipmentCxkgView.getText().toString());
        List<Switch> switchList = new ArrayList<>();
        for(int i = 0;i<number;i++){
            Switch sw = new Switch();
            sw.setId(UuidUtils.getStringID());
            sw.setName("出线开关"+f1.format(i+1));
            sw.setEquipmentId(equipmentId);
            switchList.add(sw);
        }
        switchUtil.insertMultSwitch(switchList);
        showDataView();

    }

    private void showData(List<Switch> titleData){
        switchTable.setTableData(null);
        List<ShowSwitch> showSwitches = new ArrayList<>();
        for (int i = 0; i < titleData.size(); i++) {
            final Switch aSwitch = titleData.get(i);
            ShowSwitch showSwitch = new ShowSwitch();
            showSwitch.setId(aSwitch.getId());
            showSwitch.setXh(String.valueOf(i+1));
            showSwitch.setName(aSwitch.getName());
            if(switchEquipmentUtil.querySwitchEquipmentBySid(aSwitch.getId()).size()==0){
                showSwitch.setZt("未连接");
            }else{
                showSwitch.setZt("已连接");
            }
            showSwitches.add(showSwitch);
        }

        if(showSwitches.size()>0){
            switchTable.setVisibility(View.VISIBLE);
            switchTable.setData(showSwitches);
            switchTable.getTableData().setOnRowClickListener(new TableData.OnRowClickListener() {
                @Override
                public void onClick(Column column, Object o, int col, int row) {
                    new PopWindow.Builder(PdxEquipmentActivity.this)
                            .setStyle(PopWindow.PopWindowStyle.PopUp)
                            .setTitle("你确定要删除当前数据！！")
                            .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                                @Override
                                public void onClick() {
                                    if(switchEquipmentUtil.querySwitchEquipmentBySid(titleData.get(row).getId()).size()>0){
                                        Toasty.error(getApplicationContext(), "开关已连接无法删除！", Toast.LENGTH_LONG, true).show();
                                    }else{
                                        switchUtil.deleteSwitch(titleData.get(row));
                                        showDataView();
                                    }

                                }
                            }))
                            .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                            .show();
                }
            });
        }else{
            switchTable.setVisibility(View.GONE);
        }
    }

    private void deleteDataKg(Switch s){
        new PopWindow.Builder(this)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .setTitle("你确定要删除当前数据！！")
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        if(switchEquipmentUtil.querySwitchEquipmentBySid(s.getId()).size()>0){
                            Toasty.error(getApplicationContext(), "开关已连接无法删除！", Toast.LENGTH_LONG, true).show();
                        }else{
                            switchUtil.deleteSwitch(s);
                            showDataView();
                        }

                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .show();
    }

    @Override
    public void onClick(View view) {
        if(view == qxxxRight){
            openMenu(qxxxRight, Arrays.asList(new OptionMenu(R.string.qxxx_1),new OptionMenu(R.string.qxxx_2),new OptionMenu(R.string.qxxx_3),
                    new OptionMenu(R.string.qxxx_5),new OptionMenu(R.string.qxxx_6),new OptionMenu(R.string.qxxx_7),
                    new OptionMenu(R.string.qxxx_8),new OptionMenu(R.string.qxxx_9),new OptionMenu(R.string.qxxx_10),
                    new OptionMenu(R.string.qxxx_11),new OptionMenu(R.string.qxxx_12),new OptionMenu(R.string.qxxx_13),
                    new OptionMenu(R.string.qxxx_14),new OptionMenu(R.string.qxxx_15),new OptionMenu(R.string.qxxx_16),new OptionMenu(R.string.qxxx_17)),qxxxView);
        }
        if(view == saveEquipmentView){
            saveData();
        }
        if(view == addswitch){

            if(null == dyEquipmentUtil.listOneDyEquipment(equipmentId)){
                Toasty.error(getApplicationContext(), "请先保存配电箱", Toast.LENGTH_LONG, true).show();
                return;
            }
            if(switchUtil.querySwitchByeId(equipmentId).size()==0){
                if(Utils.isNumeric(equipmentCxkgView.getText()==null?"":equipmentCxkgView.getText().toString()) && Integer.valueOf(equipmentCxkgView.getText().toString())<=100){
                    addKg();
                }else{
                    Toasty.error(getApplicationContext(), "正确输入开关数量（必须小于100）", Toast.LENGTH_LONG, true).show();
                    return;
                }
            }else{
                Toasty.error(getApplicationContext(), "已存在开关不能添加", Toast.LENGTH_LONG, true).show();
                return;
            }
        }
    }

    private void openMenu(View view, List<OptionMenu> optionMenus, ClearEditText contentView){
        PopupMenuView menuView = new PopupMenuView(getApplicationContext());
        menuView.setMenuItems(optionMenus);
        menuView.setOrientation(LinearLayout.VERTICAL);
        menuView.setOnMenuClickListener(new OptionMenuView.OnOptionMenuClickListener() {
            @Override
            public boolean onOptionMenuClick(int position, OptionMenu menu) {
                contentView.setText(menu.getTitleRes());
                return true;
            }
        });

        menuView.show(view);
    }

    private void saveData(){
        DyEquipment equipment;
        String name = autoCompleteTextViewNameView.getText()==null?"":autoCompleteTextViewNameView.getText().toString();
        if(name.equals("")){
            Toasty.error(getApplicationContext(), "设备名称不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        if((dyEquipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).size()>0 && isNew) || (dyEquipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).size()>0 && !dyEquipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).get(0).getId().equals(equipmentId))){
            Toasty.error(getApplicationContext(), "设备已存在", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(isNew){
            equipment = new DyEquipment();
        }else{
            equipment = dyEquipmentUtil.listOneDyEquipment(equipmentId);
        }

        equipment.setId(equipmentId);
        equipment.setName(name);
        equipment.setLon(Double.valueOf(lonView.getText().toString()));
        equipment.setLat(Double.valueOf(latView.getText().toString()));
        equipment.setType(typeView.getText().toString());
        equipment.setCxdxxh(cxdlxhView.getText().toString());
        equipment.setLxfs(ljfsView.getText().toString());
        equipment.setQxxx(qxxxView.getText()==null?"":qxxxView.getText().toString());
        equipment.setSbzt(sbztView.getText().toString());
        equipment.setPreviousEquipmentId(clickEquipmentId);
        equipment.setCreateTime(new Date());
        equipment.setAreaId(lineId);
        if(isNew){
            dyEquipmentUtil.insertDyEquipment(equipment);
            DyEquipmentLine equipmentLine = new DyEquipmentLine();
            equipmentLine.setId(UuidUtils.getStringID());
            equipmentLine.setStartEquipmentId(clickEquipmentId);
            equipmentLine.setEndEquipmentId(equipmentId);
            equipmentLine.setType("51");
            equipmentLine.setLineId(lineId);
            equipmentLineUtil.insertDyEquipmentLine(equipmentLine);
        }else{
            dyEquipmentUtil.updateDyEquipment(equipment);
        }

        if(!clickSwitchId.equals("")){
            List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
            for(SwitchEquipment switchEquipment :switchEquipments){
                switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
            }
            SwitchEquipment switchEquipment = new SwitchEquipment();
            switchEquipment.setId(UuidUtils.getStringID());
            switchEquipment.setSid(clickSwitchId);
            switchEquipment.setEid(equipmentId);
            switchEquipmentUtil.insertSwitchEquipment(switchEquipment);
        }
        isNew = false;
        Toasty.success(getApplicationContext(), "保存成功", Toast.LENGTH_LONG, true).show();
    }

    @Override
    public void onClickPhotoListener(String type) {
        photoType = type;
    }

    @Override
    public void openPhotoView(String path) {
        Intent intent = new Intent(PdxEquipmentActivity.this,PhotoDetailActivity.class);
        intent.putExtra("filePath",path);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(photoType.equals("qm")) {
            equipmentQmPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("mp")) {
            equipmentMpPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("qx")) {
            equipmentQxPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
    }
}